<?php

class Ext_Avatar_Save
{
    protected $_imageId;
    
    const IMAGE_RECORD_NOT_FOUND   = 'imageRecordNotFound';
    protected $_messageTemplates = array(
        self::IMAGE_RECORD_NOT_FOUND     => "Image record not found.",
    );
    protected $_messager;
    
    public function __construct($imageId)
    {
        $this->_imageId = $imageId;
        $this->_messager = new Ext_Messager($this->_messageTemplates);
    }
    
    public function save($settings)
    {
        $result = array(
            'code'        => Ext_Avatar_Save_Result::FAILURE,
            'datas'       => array(),
            'messages'    => array(),
        );
        
        $image = new Ext_Image_Show();
        $image->build($this->_imageId);
        $sourceImage = $image->source;
        if(!$sourceImage)
        {
            $result['messages'][] = $this->_messager->addMessage(self::IMAGE_RECORD_NOT_FOUND);
            return new Ext_Avatar_Save_Result($result['code'], $result['datas'], $result['messages']);
        }
        
        $downloader = new Ext_Image_Download($sourceImage);
        $downloadResultor = $downloader->download();
        if(!$downloadResultor->isValid())
        {
            $result['messages'] = $downloadResultor->getMessages();
            return new Ext_Avatar_Save_Result($result['code'], $result['videoId'], $result['messages']);
        }
        $sourceImageFile = $downloadResultor->getData();
        
        $sourceMd5sum = md5_file($sourceImageFile);
        $fileExt  = Ext_Utility_File::getImageType($sourceImageFile);
        $config = Ext_Config::getInstance()->getConfig('image');
        $avatarImageFile  = rtrim($config->graphics->tmp, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'avatar' . DIRECTORY_SEPARATOR . $sourceMd5sum.".".$fileExt;
        
        $cropzoomer = Ext_Cropzoom::getInstance();
        $cropzoomer->setSourceImage($sourceImageFile);
        $cropzoomer->setDestinationImage($avatarImageFile);
        $cropzoomer->graphics($settings);

        $adapter = new Ext_Avatar_Save_Adapter();
        $saveResultor = $adapter->save($avatarImageFile);
        if(!$saveResultor->isValid())
        {
            $result['messages'] = $saveResultor->getMessages();
            return new Ext_Avatar_Save_Result($result['code'], $result['data'], $result['messages']);
        }
        $avatarId = $saveResultor->getData();
        
        $result['code'] = Ext_Avatar_Save_Result::SUCCESS;
        $result['data'] = $avatarId;
        return new Ext_Avatar_Save_Result($result['code'], $result['data'], $result['messages']);
     }
    
}
